var app = getApp();
var time = require('../../../utils/util.js');
Page({
  data: {
    getBooksByCondition: app.globalData.bookUrl + '/book/getBooks.do',
    getReaderByBookId: app.globalData.bookUrl + '/book/lastBorrowing.do',
    getBookType: app.globalData.bookUrl + '/book/bookType.do',

    borrow: app.globalData.bookUrl + '/user/useBook.do',
    register: app.globalData.bookUrl + '/user/userRegister.do', //注册
    userInfo: app.globalData.bookUrl + '/user/userInfo.do', //判断是否已注册
    getBookType: app.globalData.bookUrl + '/book/bookType.do',
    notReturned: app.globalData.bookUrl + '/user/getBorrowing.do', //获取当前用户未归还图书id
    backBook: app.globalData.bookUrl + '/user/backBook.do',
    getEvaluateURL: app.globalData.bookUrl + '/evaluate/selectEvaluate.do',//查询评价
    subPraiseURL: app.globalData.bookUrl + '/evaluate/praise.do',//上传点赞
    getBorrowingsURL: app.globalData.bookUrl + '/Borrowing/getBorrowings.do',//借阅记录
    praiseURL: app.globalData.bookUrl + '/evaluate/praise.do',//点赞记录
    hiddenmodalput: true,
    readerNameing: "",
    bookidL: '',
    sumBorrowingsList: [],
    hidden: 'false',
    evaluateList: [],
    scanflag: 0,
    color:'',
    // num: 4,//后端给的分数，显示的星星
    illume: '',//点亮的星星数
    illume_no: '',//没有点亮的星星数
    _num: 0,
  },
  modalinput: function () {
    this.setData({
      hiddenmodalput: !this.data.hiddenmodalput
    })
  },
  getReadersName: function (e) {
    var that = this;
    that.setData({
      readerNameing: e.detail.value
    });
  },
  //取消按钮  
  cancel: function () {
    this.setData({
      hiddenmodalput: true
    });
  },

  //确认  
  confirm: function () {
    var that = this;
    if (that.data.readerNameing == "") {
      wx.showToast({
        title: '请填写姓名',
        image: '../../images/icon/fail.png',
        duration: 2000
      })
      that.setData({
        hiddenmodalput: !that.data.hiddenmodalput
      })
    } else {
      that.setData({
        readerName: that.data.readerNameing
      });
      wx.showToast({
        title: '提交成功',
        icon: 'success',
        duration: 2000
      })
      that.setData({
        hiddenmodalput: true
      })
      that.userRegister(that.data.register, that.data.openId, that.data.nickName, that.data.avatarUrl, that.data.readerName);
    }
  },
  onShow: function (e) {
    var that = this;
    that.getBooksById();
  },
  onLoad: function (options) {
    var that = this;
    var isBackEstimate = options.isBackEstimate;
    that.setData({
      isBackEstimate: isBackEstimate
    });
    wx.getStorage({
      key: 'openid',
      success(res) {
        that.setData({
          openId: res.data
        });
      }
    })
    if (isBackEstimate != 'yes') {//判断是否是评价返回的此页面
      var bookId = options.bookId;
      that.setData({
        bookId: bookId
      });
      var bookType = options.bookType;
      that.setData({
        bookType: bookType
      });
     
      wx.setStorageSync('bookId', bookId);
      wx.setStorageSync('bookType', bookType);
    }
    that.getBooksById();
    // that.getBookType();
    that.getReaderById();
 
  },
  onUnload: function (e) {
    var that = this;
    console.log("借书页返回")
    var estimateBack = that.data.isBackEstimate
    if (estimateBack == 'yes') {
      wx.switchTab({
        url: '../../library/library'
      })
    } else {
      wx.switchTab({
        url: '../library/library'
      })
    }
  },
  // getBookType: function () {
  //   var that = this;
  //   var getBookType = that.data.getBookType;

  //   wx.request({
  //     url: getBookType,
  //     data: {},
  //     method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
  //     header: {
  //       "Content-Type": "application/x-www-form-urlencoded"
  //     },
  //     success: function (res) {
  //       console.log(res);
  //       that.showBookType(res.data.data); //向前台传递数据
  //       that.getBooksById();
  //     },
  //     fail: function (error) {
  //       // fail
  //       console.log(error)
  //     }
  //   })
  // },
  // showBookType: function (allBookType) {
  //   var that = this;
  //   var bookType = [];
  //   bookType.push("全部");
  //   if (allBookType.size > 0) {
  //     for (var idx in allBookType.content) {
  //       var content = allBookType.content[idx];
  //       var bookTypeName = content.bookTypeName;
  //       bookType.push(bookTypeName);
  //       that.setData({
  //         bookTypeList: bookType
  //       });
  //     }
  //   } else {
  //     console.log("没有该分类");
  //   }
  // },
  getBooksById: function () {
    var that = this;
    var getBooksByCondition = that.data.getBooksByCondition; //获取图书URL
    var bookId = wx.getStorageSync('bookId');
    wx.request({
      url: getBooksByCondition,
      data: {
        bookId: bookId
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        console.log(res);
        that.showAllBooksByBookId(res.data.data); //向前台传递数据
        that.getTwoEvaluate();
        that.getThreeBorrowings();
      },
      fail: function (error) {
        // fail
        console.log(error)
      }
    })
  },
  getReaderById: function (bookId) {
    var that = this;
    var getReaderByBookId = that.data.getReaderByBookId; //获取图书URL
    var bookId = wx.getStorageSync('bookId');
    wx.request({
      url: getReaderByBookId,
      data: {
        bookId: bookId
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        console.log(res);
        that.showReaderByBookId(res.data.data); //向前台传递数据
      },
      fail: function (error) {
        // fail
        console.log(error)
      }
    })
  },
  getTwoEvaluate: function () {
    var that = this;
    wx.request({
      url: that.data.getEvaluateURL,
      data: {
        bookName: that.data.bookName,
        openid: that.data.openId,
        praise: "1",
        size: 2,
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        that.showTwoEvaluate(res.data.data); //向前台传递数据
      },
      fail: function (error) {
        // fail
        console.log(error)
      }
    })
  },
  getThreeBorrowings: function () {
    var that = this;
    wx.request({
      url: that.data.getBorrowingsURL,
      data: {
        bookName: that.data.bookName,
        size: 3,
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        console.log(res.data.data)
        that.showThreeBorrowingsBooks(res.data.data); //向前台传递数据
      },
      fail: function (error) {
        // fail
        console.log(error)
      }
    })
  },
  showThreeBorrowingsBooks: function (sumBorrowing) {
    var that = this;
    var sumBorrowings = [];
    if (sumBorrowing != null) {
      for (var idx in sumBorrowing.content) {
        var content = sumBorrowing.content[idx];
        var readersName = content.readersName;
        var headImg = content.headImg;
        var borrowingTime = time.formatTime(content.borrowingTime, 'Y-M-D h:m:s');
        var temp = {
          readersName: readersName,
          headImg: headImg,
          borrowingTime: borrowingTime
        }
        sumBorrowings.push(temp);
      }
      that.setData({
        sumBorrowingsList: sumBorrowings
      });
    }
  },
  getFeeling: function (e) {
    var that =this;
    that.setData({
      color: "#19b5ee"
    })
    wx.showLoading({
      title: '玩命打开中',
    })
    wx.downloadFile({
      url: app.globalData.bookUrl + encodeURIComponent(e.target.id).replace(/\%2F/g, "/"),
      success(res) {
        wx.hideLoading();
        const filePath = res.tempFilePath
        wx.openDocument({
          filePath,
          success(res) {
            console.log('打开文档成功')
          },
          fail: function (error) {
            // fail
            wx.showToast({
              title: '打开失败',
              duration: 1000,
              image: '../../../images/icon/fail.png',
            })
          }
        })
      }
    })
  },
  showTwoEvaluate: function (evaluate) {
    var that = this;
    var evaluates = [];
    if (evaluate != null) {
      for (var idx in evaluate.content) {
        var content = evaluate.content[idx];
        var bookScore = content.bookScore;
        var evaluateContent = content.evaluateContent;
        var readersName = content.readersName;
        var headImg = content.headImg;
        var evaluateFeeling = content.evaluateFeeling;
        var praise = content.praise;
        var evaluateId = content.evaluateId;
        var ispraise = content.ispraise;
        var createTime = time.formatTime(content.createTime, 'Y-M-D h:m:s');
        var temp = {
          illume: bookScore,
          illume_no: 5 - bookScore,
          readersName: readersName,
          headImg: headImg,
          createTime: createTime,
          praise: praise,
          ispraise: ispraise,
          evaluateId: evaluateId,
          evaluateFeeling: evaluateFeeling,
          evaluateContent: evaluateContent,
        }
        evaluates.push(temp);
      }
      that.setData({
        evaluateList: evaluates
      });
    }
  },
  showAllBooksByBookId: function (BooksById) {
    var that = this;
    var books = [];
    if (BooksById != null) {
      // if (BooksById.content.length > 0) {
      // for (var idx in BooksById.content) {
      var content = BooksById.content[0];
      var bookImgSource = app.globalData.bookUrl + content.bookImg + '?' + Math.random() / 9999;
      var createTimeSource = time.formatTime(content.createTime, 'Y-M-D h:m:s');
      // var bookTypeIdSource = content.bookTypeId;
      // var types = that.data.bookTypeList;
      // var typeName = types[bookTypeIdSource];
      var bookType = wx.getStorageSync('bookType');
      var temp = {
        bookId: content.bookId,
        bookImg: bookImgSource,
        bookName: content.bookName,
        createTime: createTimeSource,
        bookAuthor: content.bookAuthor,
        bookState: content.bookState,
        bookType: bookType,
        bookSynopsis: content.bookSynopsis,
        authorSynopsis: content.authorSynopsis
      }
      books.push(temp);
      that.setData({
        bookName: content.bookName,
        booklistbyid: books
      });
      // }
    } else {
      console.log("loan页没有该图书");
    }
  },
  showReaderByBookId: function (readerById) {
    if (readerById != null) {
      var reader = {
        readersName: readerById.readersName,
        headImg: readerById.headImg,
        nickName: readerById.nickName,
        borrowingTime: time.formatTime(readerById.borrowingTime, 'Y-M-D h:m:s')
      }
      this.setData({
        readerbyid: reader
      });
    } else {
      console.log("暂无数据");
    }
  },
  // 更改点赞状态
  onCollectionTap: function (event) {
    // 获取当前点击下标
    var that = this;
    var evaluateId = event.currentTarget.dataset.id;
    var collected = event.currentTarget.dataset.index;
    if (collected == 0) { //如果是没点赞+1
      collected =  1;
    } else {
      collected = 0;
    }
    // that.selectPraise(evaluateId).then(function(isParise){
    //    collected=isParise
    // })
    wx.request({
      url: that.data.praiseURL,
      data: {
        evaluateId: evaluateId,
        openid: that.data.openId,
        praise: collected,
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        that.getTwoEvaluate(); //向前台传递数据
      },
      fail: function (error) {
        // fail
        console.log(error)
      }
    })

  },
  //评价——查看全部
  all: function () {
    var that = this;
    wx.navigateTo({
      url: "../check/check?bookName=" + that.data.bookName
    })
  },
  //借阅历史——查看更多
  history_all: function () {
    var that = this;
    wx.navigateTo({
      url: "../history/history?bookName=" + that.data.bookName
    })
  },
  //评价
  appraise: function () {
    var that = this;
    wx.navigateTo({
      url: "../estimate/estimate?bookId=" + that.data.bookId + "&bookName=" + that.data.bookName + "&openId=" + that.data.openId + "&borrowFlag=" + 0
    })
  },
  //显示/隐藏  全部文章
  clickNum: function (e) {
    var thisnum = e.target.dataset.num
    if (thisnum == 1) {
      this.setData({
        _num: 0
      })
    } else {
      this.setData({
        _num: 1
      })
    }
  }, 
})